package com.sx.service.design;

import com.sx.basic.pageable.Condition;
import com.sx.basic.service.BasicService;
import com.sx.basic.service.impl.BasicServiceImpl;
import com.sx.dao.design.DesignParamsRepository;
import com.sx.design.IDesignParamsService;
import com.sx.entity.design.DesignParamsEntity;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author AdinZ
 * @date 2020/11/18 10:12
 */
@Service
public class DesignParamsService extends BasicServiceImpl<DesignParamsRepository, DesignParamsEntity,Long>
        implements BasicService<DesignParamsEntity,Long>, IDesignParamsService {
    @Override
    public void deleteByModuleId(long moduleId) {
        this.delete(new Condition().eq("module_id",moduleId));
    }

    @Override
    public void putParams(long moduleId, List<DesignParamsEntity> list) {
        list.forEach(e -> {
            e.setModuleId(moduleId);
            e.setPid(0);
            this.save(e);
            if (e.getChild() != null && e.getChild().size() > 0)
                this.putParams(moduleId, e.getId(), e.getChild());
        });
    }

    @Override
    public List<DesignParamsEntity> findTree(long moduleId) {
        List<DesignParamsEntity> list = this.repository.findAll((Specification<DesignParamsEntity>) (root, cq, cb) -> cb.equal(root.get("moduleId"),moduleId), Sort.by(Sort.Direction.ASC,"sort"));
        return DesignParamsEntity.toTree(list,0);
    }


    private void putParams(long moduleId,long pid,List<DesignParamsEntity> list) {
        list.forEach(e -> {
            e.setModuleId(moduleId);
            e.setPid(pid);
            this.save(e);
            if (e.getChild() != null && e.getChild().size() > 0) {
                this.putParams(moduleId, e.getId(), e.getChild());
            }
        });
    }

}
